******************************************************************
*** Figures 9/E.11: Pay Internal Medicine the same as Dermatology

    foreach modeltype in RF 2SLS {
	
		import delimited using "${mypath}/intermediate_csv/estimates-02-group_level_cntf_and_elast_`modeltype'.csv", clear varnames(1)
		destring score_group, replace
		destring nrmp_spec_code, replace 
		ren (nrmp_spec_code nrmp_spec_desc) (spec_category_code spec_category_desc)
		

		keep share_imsameasderm share_in_spec_pred count_byscore spec_category_desc	score_group spec_category_code
		foreach v of varlist share*{
			destring `v', replace
		}
		
		* Among people with a given USMLE score, what share chose a specialty X
		gen cntf_share_in_spec_byscore=share_imsameasderm
			
		* Observed, predicted, and counterfactual counts of people within each score-specialty cell
		*** These add up to the same counts as observed counts within a score group, 
		*** but not within a specialty (the model doesn't impose that)
		
		* Observed = count_byscore_byspeccat
		* Predicted at baseline 
		gen count_byscore_byspeccat_pred=share_in_spec_pred*count_byscore
		* Counterfactual 
		gen count_byscore_byspeccat_cntf=cntf_share_in_spec_byscore*count_byscore

		* Observed, predicted, and counterfactual counts of people within each specialty
			
		* Observed = count_byspeccat
		* Predicted at baseline
		egen count_byspeccat_pred=sum(count_byscore_byspeccat_pred), by(spec_category_desc)
		* Counterfactual 
		egen count_byspeccat_cntf=sum(count_byscore_byspeccat_cntf), by(spec_category_desc)
			
		* Predicted and counterfactual shares: 
		* Among people who chose specialty X, what share had USMLE score X 
		gen share_in_score_byspec_pred=count_byscore_byspeccat_pred/count_byspeccat_pred
		gen cntf_share_in_score_byspec=count_byscore_byspeccat_cntf/count_byspeccat_cntf
			
		* Change in shares within a score group (across specialty) and 
		* within a specialty (across score groups) 
		gen chng_share_in_spec_byscore=cntf_share_in_spec_byscore-share_in_spec_pred
		gen chng_share_in_score_byspec=cntf_share_in_score_byspec-share_in_score_byspec_pred
				
		* Plot predicted and counterfactual distribution of scores in 
		* IM and Dermatology

		gen score_avg = score_group - 5
		egen score = group(score_group)	
		tostring score_group, replace

		foreach score of numl 200(10)260 {
			replace score_group = string(`score'-10) + "s" if score_group == "`score'"
		}
		replace score_group = "> 260" if score_group == "270"
		replace score_group = "{&le} 190" if score_group == "190"

		* Shift in mean STEP score in all specialties
		* Compute observed mean score and simulated mean score by specialty 
		gen aux1 = score_avg * share_in_score_byspec_pred
		bys spec_category_*: egen avg_score = total(aux1)
			
		gen aux2 = score_avg * cntf_share_in_score_byspec
		bys spec_category_*: egen cntf_avg_score = total(aux2)
				
		drop aux*
				
		* Labels
		egen aux = group(spec_category_code)
		gen nrmp_spec_labels = aux 
		drop aux 
		labmask nrmp_spec_labels, values(spec_category_desc)
		labmask score, values(score_group)
		
		* Locals 
		qui ta score
			loc noscore = `r(r)'
		qui su avg_score if spec_category_code == 5
			loc avg_score5 = round(`r(mean)',0.1)
			loc pcm_avg = (`r(mean)'-170)/10 
		qui su cntf_avg_score if spec_category_code == 5
			loc cntf_avg_score5 =  round(`r(mean)',0.1)
			loc cntf_pcm_avg = (`r(mean)'-170)/10
		
		* Assigns location on graph to elements
		local yht "0.32"
		local yht_ct "0.315"
		if "`modeltype'"=="2SLS"{
			local yht "0.32"
			local yht_ct "0.315"
		}
		
		#d ;			
		tw (bar share_in_score_byspec_pred score if spec_category_code == 5, lcolor(eltblue) fcolor(eltblue%40)) 
			(bar cntf_share_in_score_byspec score if spec_category_code == 5, lcolor("8 48 107") lpattern(shortdash) fcolor(none) ), 
			xlabel(1(1)`noscore',valuelabel nogrid labsize(medsmall))
			ylab(0(0.05)0.3, nogrid labsize(medsmall))
			yline(0(0.05)0.25, lcolor(gs12) lpattern(dot) lwidth(thin)) 
			xline(0.5(1)`=`noscore'+0.5', lcolor(gs12) lpattern(dot) lwidth(thin)) 
			xline(`pcm_avg', lc(cranberry) lpattern(solid))
			text(`yht' `=`pcm_avg'-0.6' "Avg. USMLE" " Score = `avg_score5'", color(cranberry) placement(c) size(small) box bcolor(white)) 
			xline(`cntf_pcm_avg', lc(cranberry) lpattern(shortdash)) 
			text(`yht_ct' `=`cntf_pcm_avg'+0.6' "Counterfactual" "Avg. USMLE" "Score = `cntf_avg_score5'", color(cranberry) placement(c) size(small) box bcolor(white))  
			title("Share of Applicants", size(medsmall) placement(9) span justification(left) col(black)) 
			ytitle("") xtitle("USMLE Step 1 Scores", size(medsmall)) legend(order(1  "Baseline" 2 "Counterfactual") pos(6)rows(1) size(medium)) 
		;
		#d cr
		if "`modeltype'"=="RF"{
			graph export "${individ_figs}/counterfactuals_imsameasderm.eps", replace
		}
		else if "`modeltype'"=="2SLS"{
			graph export "${individ_figs}/counterfactuals_imsameasderm2sls.eps", replace 
		}
    }	

**************************************************************************
*** Figure 9 supporting statistics (table not in paper)
	
	** Estimation results
	import delimited using "${mypath}/intermediate_csv/estimates-02-group_level_cntf_and_elast_RF.csv", clear varnames(1) stringcols(1 2 3)
	ren nrmp_* *
	keep score_group spec* share* count*
	foreach v of varlist share*{
		destring `v', replace
	}
	
	** Counts at speciality-score level
	gen count_base=share_in_spec_pred*count_byscore 
	gen count_cntf=share_imsameasderm*count_byscore
		
	** High score vs. everyone else
	replace score_group = "_high" if inlist(score_group, "270", "260")
	replace score_group = "_low" if score_group != "_high"

	** Internal Medicine vs. everyone else 
	replace spec_desc = "Other" if spec_code !="5"
	
	** Table of baseline and counterfactual counts
	keep spec_desc score_group count_base count_cntf
	collapse (sum) count_*, by(spec_desc score_group)
	foreach v of varlist count*{
		replace `v' = round(`v')
	}
	reshape wide count_base count_cntf, i(spec_desc) j(score_group) string
	expand 2, gen(tot)
	replace spec_desc = "Total" if tot==1
	collapse (sum) count*, by(spec_desc)
	
	gen count_base_spec = count_base_low + count_base_high
	gen count_cntf_spec = count_cntf_low + count_cntf_high
	order spec_desc count_base_low count_base_high count_base_spec count_cntf_low count_cntf_high count_cntf_spec
	sort spec_desc
	replace spec_desc = "All Specialities" if spec_desc=="Total"
	
	texdoc init "${tables}/ancillary_cntf_counts.tex", replace 
	
	tex \begin{table}[h!] 
	tex \caption{\bf Pay IM Same as Dermatology: Baseline and Counterfactual Counts \label{tab:specchoice_ancillary_cntf_stats}} 
	tex \begin{center}
	tex \resizebox{1\textwidth}{!}{		
	tex \begin{tabular}{lcccccc} \midrule \midrule \\
	tex & \multicolumn{3}{c}{Baseline} & \multicolumn{3}{c}{Counterfactual} \\ \cmidrule(lr){2-4} \cmidrule(lr){5-7} \addlinespace[0.5ex]
	tex & Score $\le 250$ & Score $> 250$ & All Score Groups & Score $\le 250$ & Score $> 250$ & All Score Groups \\ \addlinespace[0.5ex]
	tex \midrule \addlinespace[2ex]
	
	forv i=1/3{
		tex `=spec_desc[`i']' & `=count_base_low[`i']' & `=count_base_high[`i']' & `=count_base_spec[`i']' & `=count_cntf_low[`i']' & `=count_cntf_high[`i']' & `=count_cntf_spec[`i']' \\ \addlinespace[0.5ex]
	}
	
	tex \addlinespace[1ex] \hline \hline
	tex \end{tabular}
	tex }
	tex \end{center}
	* Footnote with key stats for the paper 
	local numbase = `=count_base_high[1]' 
	local denbase = `=count_base_spec[1]'
	local sharebase: di %3.2fc (`numbase' / `denbase')*100
	local sharebase "`sharebase'\%"
	local numcntf = `=count_cntf_high[1]'
	local dencntf = `=count_cntf_spec[1]'
	local sharecntf: di %3.2fc (`numcntf' / `dencntf')*100
	local sharecntf = "`sharecntf'\%"
	
	tex \footnotesize The share of physicians in internal medicine with scores $> 250$ increases from `sharebase' (`numbase'/`denbase') to `sharecntf' (`numcntf'/`dencntf') in this counterfactual.
	tex \end{table}		
	
	texdoc close

******************************************************************
*** Table 5: Speciality Choice Model

	foreach f in OLS RF 2SLS{
		import delimited using "${mypath}/intermediate_csv/estimates-01-group_level_model_`f'.csv", clear varnames(1)
		gen flag = "`f'"
		tempfile data`f'
		save `data`f''
	}
	append using `dataOLS'
	append using `dataRF'
	
	drop stars*

	// Choose standard errors 
	local sedrop cluster 
	local sekeep robust
	drop sedelta`sedrop' stderr`sedrop'
	ren *`sekeep' *
	ren (stderr sedelta) (estimate_se marg_se)

	// Two covariates need *1000 for readability 
	foreach v of varlist estimate* marg* {
		replace `v' = `v'*1000 if parm == "d_mean_sd_ptotinc" | parm == "d_mean_einsize"
		replace `v' = round(`v', 0.001)
	}
	
	// Only need one row for 2SLS first stage 
	preserve 
		keep if depvar == "d_hourly_inc_270" & parm == "270.score_group#c.d_hourly_rvus"
		foreach v of varlist estimate*{
			tostring `v', format(%05.3f) replace force
		}		
		local fspoint: di %05.3f estimate[1]
		local fsse: di %05.3f estimate_se[1]
	restore 
	keep if depvar == "LogShareDiff"
	drop depvar 
	
	// Decimal formatting 
	foreach v of varlist estimate* marg*{
		tostring `v', format("%05.3f") replace force 
		if strpos("`v'","se"){
			replace `v' = "("+`v'+")"
			replace `v' = "-" if `v' == "(.)"
		}
		replace `v' = "-" if `v' == "."
	}
			
	replace estimate = "Reference" if strpos(parm,"b.")
	replace marg     = "Reference" if estimate == "Reference" & strpos(parm, "#") & ( strpos(parm, "hourly_income") | strpos(parm, "hourly_rvus"))
	foreach v of varlist estimate_se marg_se {
		replace `v' = "-" if estimate=="Reference"
	}	
	
	* Score formatting (FEs and interactions )
	g score = substr(parm,1,3) if regexm(parm,"score")
	destring score, replace
	g interaction = string(score - 9) + "-" + string(score) if score != .
	replace interaction = "\\$>\\$ 260"          if score == 270
	replace interaction = "\\$\le\\$ 190"        if score == 190
	replace interaction = "~~" + "\(\times\) " + interaction if strpos(parm, "#") & strpos(parm, "hourly_income")
	replace interaction = "~~~~~" + interaction               if ~strpos(interaction, "~~") & interaction != ""
	
	* Main variables boldface
	ren interaction tablab 
	* Save for tables with controls/FEs/Controls
	tempfile forcontrolfespec
	save `forcontrolfespec'
	
	* Only need interaction terms for this table
	drop if strpos(parm, "score_group") & !strpos(parm, "#")
	drop if inlist(parm, "d_mean_einsize", "d_mean_sd_ptotinc", "d_share_female")
	drop if strpos(parm, "_cons")
	local speclist Derma Emerg Intern ObGyn Orthop Patho Pedia Physic Plastic Psych Radiation Radiology Surgery	nrmp_spec_code
	foreach s in `speclist'{
		drop if strpos(parm, "`s'")
	}
	* Order non-interaction term first 
	foreach v in d_mean_hourly_income d_hourly_rvus{
		replace marg=estimate if parm=="`v'"
		replace marg_se=estimate_se if parm=="`v'"
	}
	
	replace parm = "180#d_hourly_income" if parm=="d_mean_hourly_income"
	replace parm = "180#d_hourly_rvus" if parm=="d_hourly_rvus"
	replace tablab = "\bf Hourly Income" if parm=="180#d_hourly_income"
	replace tablab = "\bf Hourly RVUs" if parm=="180#d_hourly_rvus"
	
	// Long-wise table 
	texdoc init "${tables}/choice_model_combined.tex", replace
		 
	tex \begin{table}[h!] 
	tex \caption{\bf Specialty Choice Model \label{tab:specchoice_main}} 
	tex \begin{center}
	tex \resizebox{1\textwidth}{!}{		
	tex \begin{tabular}{lccccccccc}  \midrule \midrule \addlinespace[1ex] 

	tex \multicolumn{1}{c}{\multirow{3}{*}{~~~~~~~~~~~Ability Group (\$ a \$) :}} & \multicolumn{8}{c}{USMLE Step 1 Scores} \\ \cline{2-10}
	tex \multicolumn{1}{c}{} & \multirow{2}{*}{$>$ 260} & \multirow{2}{*}{251-260} &  \multirow{2}{*}{241-250} &  \multirow{2}{*}{231-240} 
	tex &  \multirow{2}{*}{221-230} &  \multirow{2}{*}{211-220} &  \multirow{2}{*}{201-210} &  \multirow{2}{*}{191-200} &  \multirow{2}{*}{$\le$ 190} \\
	tex \addlinespace[1.5ex] \midrule \addlinespace[2ex]
	
	foreach model in RF OLS 2SLS{
		if "`model'"=="RF"{
			tex \bf Panel A: Reduced Form & \\ \cmidrule(lr){1-1} \addlinespace[1ex]
		}
		if "`model'"=="OLS"{
			tex \bf Panel B: OLS & \\ \cmidrule(lr){1-1} \addlinespace[1ex]
		}
		if "`model'"=="2SLS"{
			tex \bf Panel C: 2SLS & \\ \cmidrule(lr){1-1} \addlinespace[1ex]
		}
		preserve 
			if "`model'"=="RF"{
				keep if flag == "RF"
				local mylab Coefficient on Hourly RVUs
			}
			else{
				keep if flag=="`model'"
				local mylab Coefficient on Hourly Income
			}
			gsort -parm
			ren (estimate estimate_se marg marg_se) (pt std me stdme)
			tex `mylab' &`=pt[1]'&`=pt[2]'&`=pt[3]'&`=pt[4]'&`=pt[5]'& `=pt[6]'&`=pt[7]'&`=pt[8]'&`=pt[9]' \\ 
			tex ~~~~~\(\times\) Ability Group Dummy (\$ \alpha_{a} \$) &`=std[1]'&`=std[2]'&`=std[2]'&`=std[4]'&`=std[5]'& `=std[6]'&`=std[7]'&`=std[8]'&`=std[9]' \\ 
			tex \addlinespace[1ex]	
			tex Total Marginal Effect for & `=me[1]'&`=me[2]'&`=me[3]'&`=me[4]'&`=me[5]'&`=me[6]'&`=me[7]'&`=me[8]'&`=me[10]' \\ 
			tex ~~~~~~~Ability Group \$ a \$ (\$ \alpha_{\text{base}} + \alpha_{a} \$) & `=stdme[1]'&`=stdme[2]'&`=stdme[3]'&`=stdme[4]'&`=stdme[5]'&`=stdme[6]'&`=stdme[7]'&`=stdme[8]'&`=stdme[10]' \\ 
			tex \addlinespace[2ex]
		
		restore
	}
	
	tex  \hline \hline
	tex \end{tabular}
	tex }
	tex \end{center}
	tex \end{table}	
	
	texdoc close	
	
******************************************************************
*** Table E.11: Speciality Choice Model

	// Read in the tempfile from earlier to continue cleaning 
	use `forcontrolfespec', clear
	replace tablab = "\bf Constant"                   if strpos(parm, "_cons")
	replace tablab = "~~~~~Std. Dev. Hourly Income*"    if strpos(parm, "d_mean_sd_ptotinc")
	replace tablab = "~~~~~Mean Employer Size*"         if strpos(parm, "d_mean_einsize")
	replace tablab = "~~~~~Share Female"               if strpos(parm, "share_female")
	replace parm = "OBY-GYN" if parm == "ObGyn"
	reshape wide estimate estimate_se marg marg_se n, i(parm) j(flag) string
	sort score
	ren estimate* est*	
	foreach v of varlist est* marg*{
		replace `v' = subinstr(`v', "(", "", .)
		replace `v' = subinstr(`v', ")", "", .)
	}

	capture program drop choice_model_rows
	program choice_model_rows 
		tex `=tablab[1]' & `=estRF[1]' & `=est_seRF[1]' & `=estOLS[1]' & `=est_seOLS[1]' & `=est2SLS[1]' & `=est_se2SLS[1]' \\ 
		tex \addlinespace[0.75ex]
	end
	
	// Table with all estimated parameters
	texdoc init "${tables}/spec_choice_01_model_comparison_yescon.tex", replace
	
	tex \begin{table}[h!] 
	tex \caption{\small \bf Specialty Choice Model \label{tab:specchoice_aggregate_yescon}} 
	tex \begin{center}
	tex \resizebox{1\textwidth}{!}{		
	tex \begin{tabular}{lcccccc} 
	tex \midrule \midrule 
	tex &  \multicolumn{2}{c}{Reduced Form} & \multicolumn{2}{c}{OLS} & \multicolumn{2}{c}{2SLS} \\ 
	tex \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule{6-7}
	tex & (1) & (2) & (3) & (4) & (5) & (6) \\ 
	tex  & Estimate & Standard Error & Estimate & Standard Error & Estimate & Standard Error \\ 
	tex \hline \addlinespace[2ex]
	
	preserve 
	keep if parm=="d_hourly_rvus"
	tex \bf Hourly RVUs & `=estRF[1]' & `=est_seRF[1]' & - & - & - & - \\ \addlinespace[2ex]
	restore 
	preserve 	
	keep if parm=="d_mean_hourly_income"
	tex \bf Hourly Income & - & - & `=estOLS[1]' & `=est_seOLS[1]' & `=est2SLS[1]' & `=est_se2SLS[1]' \\ \addlinespace[2ex]
	restore 

	tex \bf Hourly RVUs/Income $\times$ USMLE Score \\ \addlinespace[2ex]
	preserve 
		keep if strpos(parm, "#")
		gsort parm
		foreach v of varlist estRF est_seRF margRF marg_seRF{
			replace `v' = `v'[_n-1] if strpos(parm, "income") & missing(`v')
		}
		drop if strpos(parm, "rvus")
		replace tablab = "~~~" + tablab
		tex `=tablab[1]' & `=estRF[1]' & `=est_seRF[1]' & `=estOLS[1]' & `=est_seOLS[1]' & `=est2SLS[1]' & `=est_se2SLS[1]' \\ \addlinespace[0.75ex]
		tex `=tablab[2]' & `=estRF[2]' & `=est_seRF[2]' & `=estOLS[2]' & `=est_seOLS[2]' & `=est2SLS[2]' & `=est_se2SLS[2]' \\ \addlinespace[0.75ex]
		tex `=tablab[3]' & `=estRF[3]' & `=est_seRF[3]' & `=estOLS[3]' & `=est_seOLS[3]' & `=est2SLS[3]' & `=est_se2SLS[3]' \\ \addlinespace[0.75ex]
		tex `=tablab[4]' & `=estRF[4]' & `=est_seRF[4]' & `=estOLS[4]' & `=est_seOLS[4]' & `=est2SLS[4]' & `=est_se2SLS[4]' \\ \addlinespace[0.75ex]
		tex `=tablab[5]' & `=estRF[5]' & `=est_seRF[5]' & `=estOLS[5]' & `=est_seOLS[5]' & `=est2SLS[5]' & `=est_se2SLS[5]' \\ \addlinespace[0.75ex]
		tex `=tablab[6]' & `=estRF[6]' & `=est_seRF[6]' & `=estOLS[6]' & `=est_seOLS[6]' & `=est2SLS[6]' & `=est_se2SLS[6]' \\ \addlinespace[0.75ex]
		tex `=tablab[7]' & `=estRF[7]' & `=est_seRF[7]' & `=estOLS[7]' & `=est_seOLS[7]' & `=est2SLS[7]' & `=est_se2SLS[7]' \\ \addlinespace[0.75ex]
		tex `=tablab[8]' & `=estRF[8]' & `=est_seRF[8]' & `=estOLS[8]' & `=est_seOLS[8]' & `=est2SLS[8]' & `=est_se2SLS[8]' \\ \addlinespace[0.75ex]
		tex `=tablab[9]' & `=estRF[9]' & `=est_seRF[9]' & `=estOLS[9]' & `=est_seOLS[9]' & `=est2SLS[9]' & `=est_se2SLS[9]' \\ \addlinespace[0.75ex]
		tex \addlinespace[2ex]
	restore 

	tex \bf USMLE Score Fixed Effects \\ \addlinespace[2ex]
	foreach k of numlist 190(10)270{
		preserve
			keep if strpos(parm, "`k'") & !strpos(parm, "#") & !strpos(parm, "hourly_income")
			choice_model_rows
		restore 
	}
	tex \addlinespace[1ex]
	tex \bf Specialty Fixed Effects \\ \addlinespace[2ex]
	tex ~~~~~Anesthesiology & Reference & - & Reference & - & Reference & - \\  
	tex \addlinespace[1ex]
	local speclist Derma Emerg Intern OBY-GYN Orthop Patho Pedia Physic Plastic Psych Radiation Radiology Surgery
	foreach i in `speclist'{
		preserve 
			keep if strpos(parm, "`i'")==1
			replace tablab = "~~~~~" + parm
			choice_model_rows
		restore 
	}
	tex \addlinespace[1ex]
	tex \bf Specialty Characteristics \\ \addlinespace[2ex]
	foreach control in sd_ptotinc mean_einsize share_female{
		preserve 
			keep if strpos(parm, "`control'")
			choice_model_rows
		restore 
	}
	tex \addlinespace[1ex]
	
	tex \bf N & 750 & 750 & 750 & 750 & 750 & 750  \\ 
	
	tex \hline \addlinespace[1ex]
	tex & & & & & \multicolumn{2}{c}{\bf First Stage} \\ 
	tex \cmidrule(lr){6-7}
	tex \addlinespace[1ex]
	tex \bf Choice Model Medicare Price Instrument & - & - & - &  - & `fspoint' & `fsse' \\ \addlinespace[1ex]
	tex \bf N & - & - & - & - & 80 & 80 \\
	tex \addlinespace[1ex] 

	tex \hline \hline
	tex \end{tabular}
	tex }
	tex \end{center}
	tex \end{table}
	
	texdoc close 

***********************************************************************************
*** Table E.12-E.14: Own and Cross-Income Elasticities from Speciality Choice Model 
				
	foreach f in OLS RF 2SLS {
		import delimited using "${mypath}/intermediate_csv/estimates-02-group_level_cntf_and_elast_`f'.csv", clear varnames(1)
		gen flag = "`f'"
		tempfile data`f'
		save `data`f''
	}
	append using `dataOLS'
	append using `dataRF'
	ren (nrmp_spec_code nrmp_spec_desc) (spec_category_code spec_category_desc)
	foreach v of varlist elasticity* spec_category_code score_group share*{
		destring `v', replace
	}

		* Generate column for own- and cross-specialty elasticity
		g owneps = .
		g crosseps = . 
		levelsof spec_category_code 
		foreach spec in `r(levels)' {
			loc cross = `spec' + 1
			if inlist(`spec',5,9,18)		loc cross = `spec' - 1
			replace owneps = elasticity`spec' if spec_category_code == `spec'
			replace crosseps = elasticity`cross' if spec_category_code == `spec'
		}

		* Formatting
		tostring owneps, format("%05.3f") replace force
		tostring crosseps, format("%05.3f") replace force	
			
		* Label variable
		replace spec_category_desc = "OB-GYN" if spec_category_desc == "ObGyn"
		lab var spec_category_desc "\\$ \epsilon_{i,j}^{Income} \\$"
		
		levelsof spec_category_desc
		foreach spec in `r(levels)' {
			su spec_category_code if spec_category_desc == "`spec'"
			la var elasticity`r(mean)' "`spec'"
		}
		
		g score = "USMLE Score " + string(score_group-9) + "-" + string(score_group)
		replace score = "USMLE Score $\le$ 190" if score_group == 190
		replace score = "USMLE Score $>$ 260" if score_group == 270
		replace score = "\shortstacking{" + subinstr(score,"USMLE Score","USMLE Score \\\",.) + "}"
		
		keep score* spec_category* *eps flag 

		bys flag: gen scorelabs = -(ceil(_n/15) - 10)
		labmask scorelabs, values(score)
		gsort flag scorelabs spec_category_code // critical for locals below
		
		* Table 
		loc tableno " "	
		loc tabspec "l"
		loc cmirule " "
		loc collab " "
		loc subcollab " "
			
		levelsof scorelabs
		foreach i of numl 1(1)`=2*`r(r)'' {
			loc tableno "`tableno' & (`i')"	
			loc tabspec "`tabspec'c"
			
			if `i' <= `r(r)' {
				loc cmirule "`cmirule' \cmidrule(lr){`=2*`i''-`=2*`i'+1'} "
				loc collab " `collab' & \multicolumn{2}{c}{`: label scorelabs `i''} "
			}
			
			if `=`i'/2' == `=ceil(`i'/2)' {
				loc subcollab " `subcollab' & \shortstacking{ \large \\$ \epsilon^{\textnormal{Inc.}}_{i,j}\\$ \\ \small (\\$ i = j \\$)} "
			}
			
			if `=`i'/2' == `=ceil(`i'/2)' {
				loc subcollab " `subcollab' & \shortstacking{\large \\$ \epsilon^{\textnormal{Inc.}}_{i,j}\\$ \\ \small (\\$ i \neq j \\$)} "
			}
		}		
		
	* Construct same table for each model 
		
	foreach f in OLS RF 2SLS {
		local notelab `f'
		if "`f'"=="2SLS"{
			local notelab TSLS
		}
		preserve 	
		keep if flag=="`f'"
		local spectype "`f'"
		if "`f'"=="RF"{
			local spectype "Reduced Form"
		}
		
		texdoc init "${tables}/spec_choice_02_elast_`f'.tex", replace
			
		tex \begin{table}[h!] 
		tex \caption{\bf Own and Cross-Income Elasticities From Specialty Choice Model: `spectype' \label{tab:specchoice_elast_`f'}} 
		tex \begin{center}
		tex \resizebox{1\textwidth}{!}{		
		tex \begin{tabular}{`tabspec'}  \midrule \midrule \\
		tex `collab' \\ \addlinespace[1ex]  `cmirule' 
		tex `tableno' \\ \addlinespace[1ex]  `subcollab' \\ \addlinespace[2ex] \midrule
		
		levelsof spec_category_desc
		forvalues k = 1/`r(r)' {	
			
			tex  `=spec_category_desc[`k']' & `=owneps[`k']'  		  & `=crosseps[`k']' 
			tex								& `=owneps[`=`k'+1*15']'  & `=crosseps[`=`k'+1*15']' 
			tex								& `=owneps[`=`k'+2*15']'  & `=crosseps[`=`k'+2*15']' 
			tex								& `=owneps[`=`k'+3*15']'  & `=crosseps[`=`k'+3*15']' 
			tex								& `=owneps[`=`k'+4*15']'  & `=crosseps[`=`k'+4*15']' 
			tex								& `=owneps[`=`k'+5*15']'  & `=crosseps[`=`k'+5*15']' 
			tex								& `=owneps[`=`k'+6*15']'  & `=crosseps[`=`k'+6*15']' 
			tex								& `=owneps[`=`k'+7*15']'  & `=crosseps[`=`k'+7*15']' 
			tex								& `=owneps[`=`k'+8*15']'  & `=crosseps[`=`k'+8*15']' \\ \addlinespace[1ex] 
		}	
		
		tex \addlinespace[1ex] \hline \hline
		tex \end{tabular}
		tex }
		tex \end{center}
		tex \end{table}
		
		texdoc close	
		restore 
	}
